class CommentsController < ApplicationController
  # GET /comments
  # GET /comments.xml
  before_filter :admin?,:only=>[:update,:destroy,:index]
  before_filter :login_required,:only=>[:new,:create]
  layout "none"
  def index
    @comments = Comment.find(:all,:joins=>"as a inner join users u on a.user_id=u.id",:select=>"a.*,u.login",:conditions=>["review_id=?",params[:review_id]])
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @comments }
    end
  end

  # GET /comments/1
  # GET /comments/1.xml
  def show
    @comment = Comment.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @comment }
    end
  end

  # GET /comments/new
  # GET /comments/new.xml
  def new
    @comment = Comment.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @comment }
    end
  end

  # GET /comments/1/edit
  def edit
    @comment = Comment.find(params[:id])
  end

  # POST /comments
  # POST /comments.xml
  def create
    @review =Review.find(params[:review_id])
    @comment = @review.comments.new(params[:comment])
    @comment.user_id=session[:user_id]
    respond_to do |format|
      if @comment.save
        flash[:notice] = '回复成功！'
        format.html { redirect_to(review_path(@review)) }
        format.xml  { render :xml => @comment, :status => :created, :location => @comment }
      else  
        format.html { redirect_to(review_path(@review))}
        format.xml  { render :xml => @comment.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /comments/1
  # PUT /comments/1.xml
  def update
    @comment = Comment.find(params[:id])

    respond_to do |format|
      if @comment.update_attributes(params[:comment])
        flash[:notice] = 'Comment was successfully updated.'
        format.html { redirect_to(@comment) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @comment.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /comments/1
  # DELETE /comments/1.xml
  def destroy
    @comment = Comment.find(params[:id])
    @comment.destroy

    respond_to do |format|
      format.html { redirect_to(comments_url) }
      format.js do render :update do |page|
          page.remove("comment#{@comment.id}")
          page<<"$(\"#review_count#{@comment.review_id}\").html(parseInt($(\"#review_count#{@comment.review_id}\").html())-1);"
          #page.replace_html("review_count#{@comment.review_id}","eval(parseInt($(\"#review_count#{@comment.review_id}\").html())-1)")
        end
      end
      format.xml  { head :ok }
    end
  end

  protected
  def store_location
    session[:return_to]=review_path(params[:review_id])
  end
end
